'''
Created on Nov 11, 2011

@author: Victor Bos
'''
import copy
import sys
import os.path

def copydict(d0):
    d1 = {}
    for k in d0:
        d1[k] = copy.copy(d0[k])
    return d1

def copyset(s0):
    s1 = set()
    for e in s0:
        s1.add(copy.copy(e))
    return s1

def read_lines(infile, eolstr="#", linefunc=None):
    result = []
    for line in infile:
        eolstr_idx = -1
        if len(eolstr)>0:
            eolstr_idx = line.find(eolstr)
        if eolstr_idx>-1:
            line = line[0:eolstr_idx]
        if linefunc:
            line = linefunc(line)
        result.append(line)
    return result

def read_stripped_lines(infile, eolstr="#"):
    return read_lines(infile, eolstr, lambda l: l.strip())

######################################################################
# A two-way dictionary (or One-to-One finite function)
######################################################################
class O2ODict(dict):

    def __init__(self, d=None):
        if d is None:
            d = {}
        dict.__init__(self, d)
        self.inv = {}
        for k,v in d.items():
            self.inv[v] = k

    def __setitem__(self, k, v):
        if k in self:
            if self[k] != v:
                del self[k]
        if v in self.inv:
            del self[self.inv[v]]
            
        dict.__setitem__(self, k, v)
        self.inv[v] = k

    def __copy__(self):
        return O2ODict(self)
    
    def __delitem__(self, k):
        del self.inv[self[k]]
        dict.__delitem__(self, k)
        
    def get_inverse(self):
        return O2ODict(self.inv)

######################################################################
def tag_for_name(name):
    return name.replace(' ', '_')

def mdpath():
    f = sys.argv[0]
    if hasattr(sys, "frozen"):
        f = sys.executable
        return os.path.dirname(unicode(f, sys.getfilesystemencoding( )))
    else:
        d = os.path.realpath(unicode(f, sys.getfilesystemencoding()))
        if not os.path.isdir(d):
            d = os.path.dirname(d)
        if os.path.isfile(os.path.join(d, "md.py")):
            return d
        if os.path.isfile(os.path.join(d, "src", "md.py")):
            d = os.path.join(d, "src")
            return d
    # Now we are not sure where the md.py module is...
    return None


